package org.lee.nio.udp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Random;

/**
 * @author jackielee
 * @version 1.0
 * @description UDPClient
 * @date 2021/3/8
 **/
public class UDPClient {
    public static void main(String[] args) throws IOException {
        DatagramChannel channel = DatagramChannel.open();
        String data = "hello I'm the udp client" + new Random().nextInt(100) + ",nice to meet you.";
        ByteBuffer buffer = ByteBuffer.allocate(data.length());
        buffer.clear();
        buffer.put(data.getBytes());
        buffer.flip();
        channel.connect(new InetSocketAddress("127.0.0.1", 10086));
        channel.write(buffer);

        buffer = ByteBuffer.allocate(1024);
        channel.read(buffer);
        System.out.println("received:" + new String(buffer.array()).trim());

//        Selector selector = Selector.open();
//        channel.configureBlocking(false);
//        channel.register(selector, SelectionKey.OP_READ);
//        listen(selector);
    }

    private static void listen(Selector selector) throws IOException {
        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.keys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isReadable()) {
                    DatagramChannel channel = (DatagramChannel) key.channel();

                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    channel.read(buffer);
                    byte[] data = buffer.array();
                    System.out.println("receive:" + new String(data).trim());
                }
            }
        }
    }
}
